package com.teamit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.teamit.entity.Employee;
import com.teamit.util.db.DBHelp;
import com.teamit.util.db.RowMapper;

public class EmployeeDao {
	
	private DBHelp<Employee> db = new DBHelp<Employee>();
	public List<Employee> findByProject(String projectId){
		StringBuffer sb=new StringBuffer();
		sb.append("SELECT id,username,password,pic FROM t_employee,t_employee_project ");
		sb.append("WHERE t_employee.id=t_employee_project.employee_id ");
		sb.append("AND t_employee_project.project_id=?");
		return db.executeQueryToList(sb.toString(), new EmployeeRowMapper(), projectId);
	}
	public List<Employee> findAll(){
		String sql="select id,username,password,pic from t_employee";
		return db.executeQueryToList(sql, new EmployeeRowMapper());
	}
	public void save(Employee employee){
		String sql = "insert into t_employee(id,username,password,pic) values(?,?,?,?)";
		db.executeSQL(sql,employee.getId(),employee.getName(),employee.getPassword(),employee.getPic());
	}
	public void update(Employee employee){
		String sql = "update t_employee set username=?,password=?,pic=? where id=?";
		db.executeSQL(sql, employee.getName(),employee.getPassword(),employee.getPassword(),employee.getId());
	}
	public Employee findById(String id){
		String sql = "select id,username,password,pic from t_employee where id=?";
		return db.executeQueryToObject(sql,new EmployeeRowMapper(),id);
	}
	public Employee findByName(String username){
		String sql = "select id,username,password,pic from t_employee where username = ?";
		return db.executeQueryToObject(sql, new EmployeeRowMapper(),username);
	}
	
	private class EmployeeRowMapper implements RowMapper<Employee> {

		public Employee mapRow(ResultSet rs) throws SQLException {
			Employee employee = new Employee();
			employee.setId(rs.getString("id"));
			employee.setName(rs.getString("username"));
			employee.setPassword(rs.getString("password"));
			employee.setPic(rs.getString("pic"));
			return employee;
		}
		
	}
	
}
